package com.ly.hotel.spainterface.jg.view;

import android.app.Dialog;
import android.app.DialogFragment;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.ly.hotel.R;
import com.ly.hotel.common.MyApplication;
import com.ly.hotel.spainterface.jg.adapter.MassageItemCarAdapter;
import com.ly.hotel.spainterface.jg.adapter.MassageItemEvent;
import com.ly.hotel.spainterface.jg.bean.MassageItem;
import com.ly.hotel.spainterface.jg.bean.MassageItemCarBean;
import com.ly.hotel.spainterface.jg.bean.OnHandlerShoppingCar;
import com.ly.hotel.spainterface.jg.bean.OnOrderGoodsSuccess;
import com.ly.hotel.spainterface.jg.utils.AvoidDoubleClickedUtils;
import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;

/**
 * Created by ThinkPad on 2018/3/6.
 */

public class CustomBasketDialog extends DialogFragment implements OnOrderGoodsSuccess {

    private List<MassageItem> massageItemList = new ArrayList<>();
    private OnHandlerShoppingCar onHandlerShoppingCar;
    private TextView totalPrice;
    private TextView shoppingCarIsNone;
    private List<MassageItem> massageItems;
    private MassageItemCarAdapter carAdapter;
    private boolean isEmptyShoppingCar = false;// 对否清空了购物车


    public void setOnHandlerShoppingCar(OnHandlerShoppingCar onHandlerShoppingCar) {
        this.onHandlerShoppingCar = onHandlerShoppingCar;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    public void onStart() {
        super.onStart();
        Dialog dialog = getDialog();
        if (dialog != null) {
            DisplayMetrics dm = new DisplayMetrics();
            getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
            // 设置Dialog宽度占比为60%，高度为wrap_content
            dialog.getWindow().setLayout((int) (dm.widthPixels * 0.6), ViewGroup.LayoutParams.WRAP_CONTENT);
        }
        Window window = dialog.getWindow();
        WindowManager.LayoutParams layoutParams = window.getAttributes();
        layoutParams.windowAnimations = R.style.customDialogAnim;
        window.setAttributes(layoutParams);
    }

    @Override
    public View onCreateView(LayoutInflater inflater,  ViewGroup container,  Bundle savedInstanceState) {
        getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);

        Bundle bundle = getArguments();
        MassageItemCarBean itemCarBean = (MassageItemCarBean) bundle.getSerializable("MassageItemCarBean");
        massageItems = itemCarBean.getMassageItems();
        final String serverIP = bundle.getString("serverIP");
        final String serverPORT = bundle.getString("serverPORT");
        final String cashierIP = bundle.getString("cashierIP");
        final String cashierPORT = bundle.getString("cashierPORT");
        final int limitedGoodsNum = bundle.getInt("limitedGoodsNum");
        final String categoryName = bundle.getString("categoryName");

        View view = inflater.inflate(R.layout.jg_goods_basket_layout,container,false);
        ImageButton goodsBasketClose = view.findViewById(R.id.goods_car_close);
        Button emptyShoppingCar = view.findViewById(R.id.empty_shopping_car);
        shoppingCarIsNone = view.findViewById(R.id.shopping_car_none_tips);
        Button goodsOrder = view.findViewById(R.id.shopping_goods_order);
        totalPrice = view.findViewById(R.id.total_price);

        final ListView shoppingCarListView = view.findViewById(R.id.goods_car_listview);
        shoppingCarListView.setVerticalScrollBarEnabled(false);
        shoppingCarListView.setItemsCanFocus(true);// 设置item项中可以用遥控选择其他view

        carAdapter = new MassageItemCarAdapter(shoppingCarListView, massageItems, MyApplication.getContext(),serverIP,serverPORT,limitedGoodsNum);
        shoppingCarListView.setAdapter(carAdapter);

        massageItemList = carAdapter.getMassageItems();
        // 关闭窗口
        goodsBasketClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(AvoidDoubleClickedUtils.isNotDoubleClicked()){// 如果点击的间隔少于500毫秒
                    return;
                }

                if(isEmptyShoppingCar){
                    for(int i = 0;i < massageItemList.size();i++){
                        massageItemList.get(i).setNum(1);// 数目重置为1
                    }
                    onHandlerShoppingCar.handlerShoppingCar(massageItemList);
                }else {
                    onHandlerShoppingCar.handlerShoppingCar(massageItemList);
                }
                dismiss();
            }
        });

        setShoppingCarIsNoneTips();

        // 没有添加商品到购物车时，显示购物车为空提示
        if(massageItems.size() == 0){
            shoppingCarIsNone.setVisibility(View.VISIBLE);
        }

        // 立即下单
        goodsOrder.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(AvoidDoubleClickedUtils.isNotDoubleClicked()){// 如果点击的间隔少于500毫秒
                    return;
                }

                if(massageItemList.size() > 0){
                    MassageItemCarBean massageItemCarBean = new MassageItemCarBean();
                    massageItemCarBean.setMassageItems(massageItemList);

                    Bundle bundle = new Bundle();
                    bundle.putString("cashierIP",cashierIP);
                    bundle.putString("cashierPORT",cashierPORT);
                    bundle.putSerializable("massageItemCarBean",massageItemCarBean);
                    bundle.putString("categoryName",categoryName);

                    CustomOrderFromCarDialog orderFromCarDialog = new CustomOrderFromCarDialog();
                    orderFromCarDialog.setCancelable(false);
                    orderFromCarDialog.setOnOrderGoodsSuccess(CustomBasketDialog.this);
                    orderFromCarDialog.setArguments(bundle);
                    orderFromCarDialog.show(getFragmentManager(),"CustomOrderFromCarDialog");
                }else{
                    CustomToast customToast = CustomToast.makeText(MyApplication.getContext(),"购物车为空，请先添加商品！", Toast.LENGTH_SHORT,false);
                    customToast.setGravity(Gravity.CENTER,0,0);
                    customToast.show();
                }
            }
        });

        // 清空购物篮
        emptyShoppingCar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(AvoidDoubleClickedUtils.isNotDoubleClicked()){// 如果点击的间隔少于500毫秒
                    return;
                }
                CustomToast customToast = CustomToast.makeText(MyApplication.getContext(),"购物车已经清空！", Toast.LENGTH_SHORT,false);
                customToast.setGravity(Gravity.CENTER,0,0);
                customToast.show();
                emptyShoppingCar();
            }
        });

        return view;
    }

    public void emptyShoppingCar(){
        if(massageItems.size() > 0){
            isEmptyShoppingCar = true;// 记录已清空购物篮
            massageItems.clear();
            carAdapter.notifyDataSetChanged();
            setShoppingCarIsNoneTips();
            shoppingCarIsNone.setVisibility(View.VISIBLE);
        }
    }

    public void onEventMainThread(MassageItemEvent massageItemEvent){
        setShoppingCarIsNoneTips();
        if(massageItemList.size() == 0){
            shoppingCarIsNone.setVisibility(View.VISIBLE);
        }
    }

    // 设置合计数目
    public void setShoppingCarIsNoneTips(){
        double amountMoney = 0;
        for(int i = 0;i < massageItems.size();i ++){
            MassageItem massageItem = massageItems.get(i);
            double price = massageItem.getPrice();
            int num = massageItem.getNum();
            amountMoney += price * num;
        }
        totalPrice.setText("合计：" + amountMoney + "元");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void orderGoodsSuccess(boolean isOrderSuccess) {// 是否下单成功回调函数
        if(isOrderSuccess){
            emptyShoppingCar();
            setShoppingCarIsNoneTips();
        }
    }
}
